package com.interceptor;

import com.common.WebContextHelper;
import com.common.JSONPObjectUtil;
import com.common.JSONUtil;
import com.common.ResultUtil;
import com.entity.Manager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Manager manager = WebContextHelper.getOnLineUser();
        /*没有登录*/
        if (null == manager) {
            String requestType = request.getParameter("X-Requested-With");
            String ajax = request.getParameter("act");
            /*ajax请求*/
            String callbackParam = request.getParameter(JSONPObjectUtil.CALL_BACK_PARAM_NAME);
            if (StringUtils.isNotBlank(callbackParam)) {
                ResultUtil resultUtil = ResultUtil.newInstance();
                resultUtil.setStatus(ResultUtil.UN_LOGIN);
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(JSONUtil.object2String(JSONPObjectUtil.createJSONPObject(resultUtil)));
            } else if (null != requestType || "ajax".equals(ajax)) {
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write("{\"status\": " + ResultUtil.UN_LOGIN + "}");
            } else {
                response.sendRedirect(request.getContextPath() + "/direct/login.htm");
            }
            return false;
        }
        return super.preHandle(request, response, handler);
    }

}
